﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Configuration;

namespace IPSWeb.UserControls
{
    public partial class TextBoxEditor : System.Web.UI.UserControl
    {
        private string ConfigurationScriptDirectory; //The directory where scripts should be stored
        public string FilePath { get; set; } //If exists: the full path to the script file to edit
        private string FileContent;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                ConfigurationScriptDirectory = ConfigurationManager.AppSettings["UserScriptsDirectoryPath"];
                if (!string.IsNullOrEmpty(FilePath))
                {
                    if (File.Exists(FilePath))
                    {
                        FileContent = File.ReadAllText(FilePath);

                        tbCodeEditor.Text = FileContent;
                    }
                    tbPath.Text = FilePath;
                    tbPath.ReadOnly = true;
                }
                else
                {
                    tbPath.ReadOnly = false;
                    FileContent = "";
                }

            }
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            
            string newCode = tbCodeEditor.Text;
            string filePath = ConfigurationManager.AppSettings["UserScriptsDirectoryPath"] + "/" + tbPath.Text;
            if (string.IsNullOrEmpty(FilePath))
            {
                //CreateFile
                File.AppendAllText(filePath, newCode);
            }
            else
            {
                //Replace The File
                if (File.Exists(FilePath))
                    File.Delete(FilePath);
                if (!string.IsNullOrEmpty(newCode)) // If there is no text means to delete the file
                    File.AppendAllText(FilePath, newCode);
            }
        }
    }
}